#include "StdAfx.h"
#include "Acceptor.hpp"
#include "Server.hpp"

using namespace HpsFramework;
using namespace HpsFramework::Network;

Acceptor::Acceptor ()
{

}

Acceptor::Acceptor ( HpsFramework::Network::Server * srv )
{
	this->setServer ( srv );
}

Acceptor::~Acceptor( void )
{

}

bool HpsFramework::Network::Acceptor::handleConnection ( Network::Socket& sock, Network::Address& addr )
{

	if(!this->filterConnection ( sock, addr )) 
	{
		return false;
	}

	ClientManager* manager = this->getServer()->getClientManager();
	ClientFactory* factory = this->getServer()->getClientFactory();

	if(factory) 
	{

		Client* client = factory->createClient ( sock );
		if(client)
		{

			manager->insertClient ( client );

			if(!this->getServer()->getIoController()->associate<Client*>(client->getSocket(), client))
			{
				manager->removeClient ( client );
				factory->destroyClient ( client );
				return false; 
			}

			if ( this->getServer()->onServerConnection ( client, addr ) )
			{
				
				unsigned int recvBytes = 0, recvFlags = 0;

				client->getReader()->startTransmisson();

				int ret = WSARecv ( 
					client->getSocket(), 
					client->getReader()->getNetBuf(), 1, (LPDWORD)&recvBytes, (LPDWORD)&recvFlags, 
					client->getReader()->getNetOverlap(), NULL );

				client->onConnect(); 

				return true;

			}
			else
			{
				this->getServer()->onServerError("Server seems to be rejected the new client.", -1);
				manager->removeClient ( client );
				factory->destroyClient ( client );
			}

		}
		else
		{
			this->getServer()->onServerError("ClientFactory: Error allocating a new client instance.", -1);
		}

	}

	return false;

}

bool HpsFramework::Network::Acceptor::filterConnection( Network::Socket& sock, Network::Address& addr )
{
	return true;
}
